<?php

class deptController extends baseController
{
	public function show()
	{
		$this->assign('list',	Dept::getList());
		$this->display();
	}

    public function add()
    {
        if(is_post())
        {
            if(!fetch_a_string('name')) {
				Show::warn('名称不能为空！');
            }
			$dept_id = Dept::add(array(
				'sno_prefix' => fetch_a_string('sno_prefix'),
				'name' => fetch_a_string('name'),
			));
			if(!$dept_id) {
				Show::warning("保存失败，请检查数据重复");
			}
			else{
				LoggerHelper::manage("新建部门记录，名称'".fetch_a_string('name')."'，ID:{$dept_id}");
				Show::note('保存成功');
			}
        }

        $this->display();
    }
	
    public function modify()
    {
		$ddata = Dept::get(fetch_a_int('id'));
        if(!$ddata)
        {
            Show::warn("部门记录不存在!");
        }

        if(is_post())
        {
            if(!fetch_a_string('name')) {
				Show::warn('名称不能为空！');
            }
			$r = Dept::update($ddata['id'], array(
				'sno_prefix' => fetch_a_string('sno_prefix'),
				'name' => fetch_a_string('name'),
			));
			if($r){
				LoggerHelper::manage("编辑部门记录，原名称'{$ddata['name']}'、编号'{$ddata['sno_prefix']}'，ID:{$ddata['id']}");
				Show::note('保存成功');
			}
			else{
				Show::warn('保存失败');
			}
        }

        $this->assign('dept', $ddata);
        $this->display('dept-add');
    }

	/**
	 * 保存排序
	 */
	public function sort()
	{
		if(fetch_get('s'))
		{
			$tmp = explode(',', fetch_get('s'));
			foreach($tmp as $k=>$gid) {
				Dept::update($gid, array('sort'=>$k));
			}
			LoggerHelper::manage("修改部门排序");
			Show::notice("保存成功!");
		}
		else {
			Show::error("参数错误");
		}
	}

	/**
	 * 删除
	 */
	public function delete()
	{
		if(!fetch_get('dept_id','int')) {
			Show::error("参数错误");
		}
		if(DeptHelper::delete(fetch_get('dept_id','int'))) {
			LoggerHelper::manage("修改部门记录，ID:".fetch_get('dept_id','int'));
			Show::notice("删除成功");
		}
		else {
			Show::warning("删除失败");
		}
	}
	
	/** 部门审核人 */
	public function reviewer(){
		$id = fetch_a_int('id');
		if(!$id){
			$this->assign('list',	Dept::getList());
			return $this->display('dept-show2');
		}
		
		$dept = Dept::get($id);
		if(!$dept){
			Show::warn("无此部门");
		}
		$type2 = fetch_a_int('type')==2;
		
		if(is_post()){
			$uids = !empty($_POST['user_id']) ? array_filter(array_map('intval', $_POST['user_id'])) : null;
			Dept::update($id, array(($type2?'reviewers2':'reviewers')=>join(',', $uids)));
			LoggerHelper::manage("修改部门审核人记录，ID:{$id}");
			Show::note("操作成功");
		}
		
		$reviewers = array_filter(explode(',', $type2?$dept['reviewers2']:$dept['reviewers']));
		$this->assign('dept', $dept);
		$this->assign('users', User::getList());
		$this->assign('reviewers', $reviewers);
		$this->assign('type2', $type2);
		$this->display();
	}
	
}

?>
